<?php

namespace app\common\traits;

use ip138\Ip138;
use ShidianUtil\Utils\ConvertUtil;
use function app;
use function is_blank;

/**
 * 定位
 * Trait LocationTrait
 * @package app\common\traits
 */
trait LocationTrait
{

    private function getProvinceCityByIp($ip): array
    {
        $response = $this->getIp138()
            ->getCityByIp($ip);

        $result = (string)$response->getBody();

        if (is_blank($result)) {
            return [
                'provinceName' => '',
                'cityName' => '',
            ];
        }

        $result = ConvertUtil::jsonDecode($result);

        $provinceName = $result['data'][1] ?? '';
        $cityName = $result['data'][2] ?? '';

        return [
            'provinceName' => $provinceName,
            'cityName' => $cityName,
        ];
    }

    private function getProvinceCityByPhone($phone): array
    {
        $response = $this->getIp138()->getCityByPhone($phone);

        $result = (string)$response->getBody();

        if (is_blank($result)) {
            return [
                'provinceName' => '',
                'cityName' => '',
            ];
        }

        $result = ConvertUtil::jsonDecode($result);

        $provinceName = $result['data'][0] ?? '';
        $cityName = $result['data'][1] ?? '';

        return [
            'provinceName' => $provinceName,
            'cityName' => $cityName,
        ];
    }

    private function getIp138(): Ip138
    {
        return app(Ip138::class);
    }
}